package nf;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Scanner;

class IniParser
{
	private HashMap<String, String> map = new HashMap<>();
	private boolean loaded = false;
	private boolean errors = false;
	
	public IniParser(String fileName)
	{
		if(fileName == null)
			return;
		
		loaded = loadFile(fileName);
	}
	
	public boolean isLoaded()
	{
		return loaded;
	}
	
	private boolean processLine(String line, int l, String fileName)
	{
		line = line.trim();
		
		if(line.isEmpty())
			return false;
		
		if(line.startsWith("#") || line.startsWith(";") || line.startsWith("//"))
			return false;
		
		if(!line.contains("="))
		{
			System.out.println("Syntax error at line " + l + " \"" + line + "\" in file \"" + fileName + "\" : no '='");
			errors = true;
			return false;
		}
		
		String[] parts = line.split("=");
		//System.out.println("Parts = " + parts.length);
		if(parts.length != 2)
		{
			System.out.println("Syntax error at line " + l + " \"" + line + "\" in file \"" + fileName + "\" : multiple '='");
			errors = true;
			return false;
		}
		
		parts[0] = parts[0].trim();
		parts[1] = parts[1].trim();
		
		if(parts[0].isEmpty())
		{
			System.out.println("Syntax error at line " + l + " \"" + line + "\" in file \"" + fileName + "\" : key part empty/whitespace");
			errors = true;
			return false;
		}
		
		if(parts[1].isEmpty())
		{
			System.out.println("Syntax error at line " + l + " \"" + line + "\" in file \"" + fileName + "\" : value part empty/whitespace");
			errors = true;
			return false;
		}
		
		map.put(parts[0], parts[1]);
		return true;
	}
	
	
	
	private boolean loadFile(String fileName)
	{
		Scanner s = null;
		try
		{
			s = new Scanner(new File(fileName));
		} catch (FileNotFoundException e)
		{
			return false;
		}
		
		int l = 0;
		
		while(s.hasNext())
		{
			String line = s.nextLine();
			l++;
			processLine(line, l, fileName);
		}
		
		s.close();
		
		return true;
	}
	
	public String getString(String key, String def)
	{
		String ret = map.get(key);
		if(ret != null)
			return ret;
		else 
			return def;
	}
	
	public int getInt(String key, int def)
	{
		String ret = map.get(key);
		if(ret == null)
			return def;
		
		try
		{
			int num = Integer.parseInt(ret);
			return num;
		}
		catch(Exception e)
		{
			return def;
		}
	}
	
	public double getDouble(String key, double def)
	{
		String ret = map.get(key);
		if(ret == null)
			return def;
		
		try
		{
			double num = Double.parseDouble(ret);
			return num;
		}
		catch(Exception e)
		{
			return def;
		}
	}
	
	public boolean getBoolean(String key, boolean def)
	{
		String ret = map.get(key);
		if(ret == null)
			return def;
		
		if(ret.toLowerCase().equals("true"))
			return true;
		if(ret.toLowerCase().equals("false"))
			return false;
		
		try
		{
			int num = Integer.parseInt(ret);
			return num > 0;
		}
		catch(Exception e)
		{
			return def;
		}
	}
	
	public boolean hadErrors()
	{
		return errors;
	}
}
